import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_fancy_tree_view/flutter_fancy_tree_view.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:im_app/im/page/model/CommonModel.dart';
import 'package:im_app/im/page/view/model/DataChangeListener.dart';
import 'package:im_app/im/pojo/Enums.dart';

import 'sub/UserInfoPage.dart';
import 'model/DepartmentListModel.dart';
import 'view/LoadingView.dart';

/// 机构列表
class DepartmentListPageCubit extends StatefulWidget {

  @override
  State<StatefulWidget> createState()=>_DepartmentListPageSate();

}

class _DepartmentListPageSate extends DataChangeStateListener<DepartmentListPageCubit, DepartmentTreeNode> {

  late TreeController<DepartmentTreeNode> _treeController;
  late DepartmentListModel _departmentListModel;
  var _loadingState = LoadingState.loading;

  @override
  void initState() {
    super.initState();
    print("DepartmentListPageCubit init!!!!!!!!!!!!");
    _departmentListModel = DepartmentListModel(this);

    _treeController = TreeController(roots: dataList, childrenProvider: (DepartmentTreeNode model)=>model.children);

    _departmentListModel.loadData().then((values){
      _loadingState = LoadingState.success;
      setState(() {
        dataList.addAll(values);
        print("DepartmentListPageCubit init!!!!!!!!!!!!: ${dataList.length}");
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return LoadingView(state: _loadingState, child:
      TreeView<DepartmentTreeNode>(
        treeController: _treeController,
        physics: const BouncingScrollPhysics(),
        nodeBuilder: (BuildContext context, TreeEntry<DepartmentTreeNode> entry) {
          return _DepartmentTreeCell(
            entry: entry,
            departmentListModel: _departmentListModel,
            treeController: _treeController,
            onTap: () => _treeController.toggleExpansion(entry.node),
          );
        }
      )
    );
  }

  @override
  void dispose() {
    super.dispose();
    _treeController.dispose();
  }
}

class _DepartmentTreeCell extends StatefulWidget {
  const _DepartmentTreeCell({
    super.key,
    required this.entry,
    required this.onTap,
    required this.departmentListModel,
    required this.treeController,
  });

  final TreeEntry<DepartmentTreeNode> entry;
  final VoidCallback onTap;
  final DepartmentListModel departmentListModel;
  final TreeController treeController;

  @override
  State<StatefulWidget> createState() {
    return _DepartmentTreeCellSate();
  }
}

class _DepartmentTreeCellSate extends State<_DepartmentTreeCell> {

  var _loading = false;
  var _moreText = '加载更多';

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: pressedEvent,
      onDoubleTap: doubleTap,
      child: this.widget.entry.node.isMore?? false ? _buildMoreData() : _buildTreeNode()
    );
  }

  Widget _buildTreeNode() {
    return TreeIndentation(
      entry: this.widget.entry,
      guide: const IndentGuide.connectingLines(indent: 48),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(4, 4, 4, 4),
        child: _buildTreeCell(),
      ),
    );
  }

  Widget _buildMoreData() {
    return TreeIndentation(
      entry: this.widget.entry,
      guide: const IndentGuide.connectingLines(indent: 48),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(15, 15, 15, 15),
        child: Text(_moreText)
      )
    );
  }

  String _buildName(DepartmentTreeNode model) {
    if (model.department != null) {
      return model.department!.name??'root';
    }
    if (model.user != null) {
      return model.user!.userName!;
    }
    return '';
  }

  Widget _buildHeadIcon() {
    String assetName = '';
    if (this.widget.entry.node.department != null) {
      assetName = 'assets/svg/department.svg';
    } else if (this.widget.entry.node.user != null) {
      assetName = 'assets/svg/person.svg';
    }
    if (this.widget.entry.isExpanded) {
      return Padding(padding: EdgeInsets.only(left: 13, right: 13, top: 10, bottom: 10),
        child: SvgPicture.asset(assetName, width: 30, height: 30,
          theme: SvgTheme(currentColor: Colors.black12),),
      );
    } else {
      return Padding(padding: EdgeInsets.only(left: 13, right: 13, top: 10, bottom: 10),
        child: SvgPicture.asset(assetName, width: 30, height: 30,
          theme: SvgTheme(currentColor: Colors.black12),),
      );
    }
  }

  Widget _buildTreeCell() {
    if (_loading) {
      return Container(
        child: Row(children: [
          Container(
              child: CupertinoActivityIndicator(radius: 12,),
              margin: EdgeInsets.only(left: 19, top: 13, bottom: 13, right: 13),
          ),
          Text(_buildName(this.widget.entry.node))
        ], crossAxisAlignment: CrossAxisAlignment.center),
        // margin: EdgeInsets.only(top: 10, bottom: 10),
      );
    }
    return Row(
      children: [
        // FolderButton(
        //   icon: _buildIcon(),
        //   isOpen: this.widget.entry.hasChildren ? this.widget.entry.isExpanded : null,
        //   // onPressed: pressedEvent,
        // ),
        _buildHeadIcon(),
        Text(_buildName(this.widget.entry.node)),
      ],
    );
  }

  void pressedEvent() async {
    var departmentTreeModel = this.widget.entry.node;
    if (departmentTreeModel.isMore??false) {
      var parent = this.widget.entry.parent;
      if (parent != null) {
        int size = parent.node.children.length??0;
        if (size < 1) return;
        setState(() {
          this._moreText = '数据加载中。。。';
        });
        var datas = await this.widget.departmentListModel.loadMoreData(parent.node!);
        parent.node.children.insertAll(size-1, datas);
        setState(() {
          _moreText = '加载更多';
        });
        this.widget.treeController.rebuild();
      }

      return;
    } else if (departmentTreeModel.user != null){
      Navigator.of(context).push(new MaterialPageRoute(builder: (context1){
        return UserInfoPage(user: departmentTreeModel.user!);
      }));
    }

    if (departmentTreeModel.department != null) {
      if (departmentTreeModel.children.where((node)=>node.user != null).isEmpty) {
        startLoading();
        var datas = await this.widget.departmentListModel.loadMoreData(departmentTreeModel);
        setState(() {
          departmentTreeModel.children.addAll(datas);
          departmentTreeModel.children.add(DepartmentTreeNode.moreData());
          this._loading = false;
        });
      }
      this.widget.onTap.call();
    }
  }

  void doubleTap() {
    var departmentTreeModel = this.widget.entry.node;
    if (departmentTreeModel.user != null) {
      this.widget.treeController.toggleExpansion(this.widget.entry.parent!.node!);
    }
  }

  void startLoading() {
    setState(() {
      this._loading = true;
    });
  }

  void successLoading(){
    setState(() {
      this._loading = false;
    });
  }

}